package org.jb.coinche.server.user.impl;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.jb.coinche.client.user.UserLogin;
import org.slf4j.MDC;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;

@Singleton
public class UserLogFilter implements Filter {

	@Inject @UserLogin
	private Provider<String> userProvider;
	
	@Override
	public void destroy() {}

	@Override
	public void doFilter(
			ServletRequest request, 
			ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		String user = userProvider.get();
		
		if (user != null) {
			MDC.put("user", user );
			MDC.put("address", request.getRemoteAddr() );
		} else {
			MDC.put( "user", "none");
			MDC.put( "address", request.getRemoteAddr() );
		}
		
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {}

}